package com.zhongxi.guoyuan.fragment.beautifulStore;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.beautifulStore.NewBeautifulAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventMessage;
import com.zhongxi.guoyuan.entity.service.ServiceItemData;
import com.zhongxi.guoyuan.entity.service.ServiceResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.widget.MyListView;
import com.zhongxi.guoyuan.widget.xlistview.XListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/10/17.
 */

public class BestPriceBeautifulFragment extends BaseFragment {

    private MyListView lvList;
    private String trim;
    private NewBeautifulAdapter adapter;
    private List<ServiceItemData> list = new ArrayList<>();
    private View loadMoreView;
    private TextView text_loadmore;
    private ProgressBar progressBar;
    private int pageNum;
    private boolean isVisib;


    public BestPriceBeautifulFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            trim = getArguments().getString("trim");
//        }
        trim="";

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mei_rong, container, false);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (MyListView) getView().findViewById(R.id.lvList);
        adapter = new NewBeautifulAdapter(context, list);
        lvList.setAdapter(adapter);
        getEmpty();
        addFooterView();
    }

    private void addFooterView() {
        loadMoreView = LayoutInflater.from(getContext()).inflate(R.layout.load_moredata, null);
        text_loadmore = (TextView) loadMoreView.findViewById(R.id.text_loadmore);
        progressBar = (ProgressBar) loadMoreView.findViewById(R.id.progressbar);
        progressBar.setVisibility(View.GONE);
        loadMoreView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadMore();
            }
        });
        lvList.addFooterView(loadMoreView);
    }

    /**
     * 点击加载更多
     */
    private void loadMore() {
        text_loadmore.setText("加载中...");
        progressBar.setVisibility(View.VISIBLE);
        pageNum++;
        if (!TextUtils.isEmpty(trim)) {
            getPost();
        } else {
            getData();
        }
    }

    private void getEmpty() {
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("暂无数据,敬请期待");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser){

            isVisib =true;
            pageNum = 1;

                getData();

        }else {
            isVisib=false;
        }

    }

    private void getData() {
        String getStr = "&page=" + pageNum + "&orderby=2";
        getServer(Url.SERVICE_LIST, null, getStr, false, null, "get");
    }

    private void getPost() {
        Map<String, String> map = new HashMap<>();
        map.put("content", trim);
        String str = "&page=" + pageNum;
        getServer(Url.INNER_SERVICE, map, str, false, null, "post");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(EventMessage msg){
        pageNum=1;
        trim=msg.getMessage();
        if (isVisib){
            if (!TextUtils.isEmpty(trim)) {
                getPost();
            }else {
                getData();
            }
        }

    }
    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(context, ProjectDetailActivity.class);
                intent.putExtra("id", list.get(i).getId());
                startActivity(intent);
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        ServiceResult serviceResult = gson.fromJson(response, ServiceResult.class);
        if (serviceResult.getSafeobj() != null && !"".equals(serviceResult.getSafeobj())) {
            MyApplication.getInstance().setSpValue(serviceResult.getSafeobj());
        }
        if (pageNum > 1) {
            if (null == serviceResult.getData() || serviceResult.getData().size() == 0) {
                showShortToast("没有更多了");
                text_loadmore.setText("戳我加载更多");
                progressBar.setVisibility(View.GONE);
            }
        }
        if (pageNum == 1) {
            list.clear();
        }
        if (!TextUtils.isEmpty(trim)) {
            if (null != serviceResult.getData() && serviceResult.getData().size() > 0) {
                list.addAll(serviceResult.getData());
            } else {

                Toast.makeText(context, "抱歉,搜索不到与”" + trim + "“相关的关键词", Toast.LENGTH_SHORT).show();
            }
        } else {
            if (null != serviceResult.getData() && serviceResult.getData().size() > 0) {
                list.addAll(serviceResult.getData());
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
